<?php
/**
 * 该页面用来获取小程序二维码
 * 1.获取access_token
 * 2.获取小程序带参数二维码
 */
const APP_ID = 'wx467336ca1bd3903b';
const APP_SECRET = '3558e551ff56a921c136eb592ae41806';

function http_get($url){
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
//    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对象
}

function http_post( $url, $post_data = '', $timeout = 5 ){
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POST, 1);
    if($post_data != ''){
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;

}

//todo 获取access_token : {"access_token":"ACCESS_TOKEN","expires_in":7200}
function get_access_token( $url ){

    $result = http_get($url);
    echo '$result:' . $result . '<br/>';
    $result_arr = json_decode( $result, true );

    if( !empty( $result_arr['access_token']) ){
        return $result_arr['access_token'];
    }else{
        return false;
    }
}

function get_qrcode( $url, $data ){

    $result = http_post($url, $data );

//    $json = json_decode( $result, true);
    return $result;

}




$url_access_token_template = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
$url_access_token = sprintf( $url_access_token_template,APP_ID,APP_SECRET );
$access_token = get_access_token( $url_access_token );

//$access_token : 10_raye4fO0yagKbQVxYWoD37ZFZ_O4iIrdQ_29Oq5qPEtibG1Yg3n6-G-wEYAFR_4iQyz2-nAa4D3CX4IKh2QPmCUG2ZzhsjcPVqneLdT10rM_o83f-MncHRW6qYTKnXwG7YVpwXySxEj5CEm0LJKiAEAGEF
//todo 输出小程序带参二维码

//$url_qrcode = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' . $access_token;
$url_qrcode = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;

$post_data = '{"page": "pages/index/index", "scene":"1", "width": 430}';
$qrcode_result = get_qrcode( $url_qrcode, $post_data );

//$img_div = "<img src='" . $qrcode_result . "' />";
//echo $img_div;

echo $qrcode_result;